package hft_suttgart.pvc;

import com.example.hft_suttgart.swp2.R;

import database.DatabaseHandler;
import database.Player;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class UserAuthentication extends Activity implements OnClickListener{

	private EditText email;
	private EditText password;
	private DatabaseHandler db;
	private Button login;
	private Button cancel;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		setContentView(R.layout.password_dialog);
		email = (EditText)findViewById(R.id.username);
		password = (EditText)findViewById(R.id.password);
		db = new DatabaseHandler(this);
		login = (Button) findViewById(R.id.login);
		cancel = (Button) findViewById(R.id.cancel);
		
		login.setOnClickListener(this);
		cancel.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.user_authentication, menu);
		return true;
	}
	
	@Override
	protected void onDestroy(){
	    // close befor super is called
	    db.close();
	    super.onDestroy();
	    Log.i("onDestroy()", "super.onDestroy may already has destroyed the DB");
	}

	@Override
	public void onClick(View component) {
		String name = email.getText().toString();
		String pword = password.getText().toString();
		
		// TODO: Obtains the password of the current user from DB
		
		switch (component.getId()) {
			case R.id.login:
				
				Player player = (name.length() > 0) ? db.getPlayer(name): new Player();				
				boolean isValidUser = pword.equals(player.getPassword());
				if (isValidUser) 
					{
						Intent intent = new Intent(this, Play_Exit_Menu.class);
						startActivity(intent);
					}
				break;
			case R.id.cancel:
				this.finish();
				break;
		}
		
	}
	
}
